package cn.qiba.sms.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import cn.qiba.sms.bo.common.SmsResult;
import cn.qiba.sms.bo.tencent.TencentSmsBO;
import cn.qiba.sms.kit.TencentSmsKit;
import cn.qiba.sms.service.ISmsService;
import com.aliyuncs.exceptions.ClientException;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TencentSmsServiceImpl implements ISmsService<TencentSmsBO> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TencentSmsKit tencentSmsKit;

    @Override
    public SmsResult send(TencentSmsBO tencentSmsBO) {
        logger.info("腾讯云短信发送参数："+JSONUtil.toJsonStr(tencentSmsBO));
        try {
            LinkedHashMap<String,Object> paramsMap = tencentSmsBO.getTemplateParam();
            List<String> templateParamsList = new ArrayList<>();
            for(Map.Entry entry:paramsMap.entrySet()){
                templateParamsList.add(entry.getValue().toString());
            }
            String[] templateParams = ArrayUtil.toArray(templateParamsList,String.class);
            templateParams = ArrayUtil.reverse(templateParams);
            String phoneNumber = tencentSmsBO.getPhoneNumber();
            Gson gson = new Gson();
            if (phoneNumber.indexOf(",") > 0) {//群发
                SmsMultiSenderResult smsMultiSenderResult = tencentSmsKit.sendMultiSms(phoneNumber.split(","), tencentSmsBO.getSignName(), tencentSmsBO.getTemplateCode(), templateParams);
                logger.info("腾讯云短信群发返回结果："+ gson.toJson(smsMultiSenderResult));
                if(smsMultiSenderResult.result == 0){
                    return SUCCESS;
                }else{
                    return new SmsResult(smsMultiSenderResult.result+"",smsMultiSenderResult.errMsg);
                }
            } else {
                SmsSingleSenderResult smsSingleSenderResult = tencentSmsKit.sendSms(phoneNumber, tencentSmsBO.getSignName(), tencentSmsBO.getTemplateCode(), templateParams);
                logger.info("腾讯云短信单发返回结果："+ gson.toJson(smsSingleSenderResult));
                if(smsSingleSenderResult.result == 0){
                    return SUCCESS;
                }else{
                    return new SmsResult(smsSingleSenderResult.result+"",smsSingleSenderResult.errMsg);
                }
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return null;
    }
}
